<template>
  <div class="history-trend-chart">
    <!-- 图表标题和说明 -->
    <div class="flex items-center justify-between mb-4">
      <div>
        <h4 class="text-lg font-semibold text-gray-800">历史成绩趋势</h4>
        <p class="text-sm text-gray-500">滚动鼠标滚轮可加载更多历史数据</p>
      </div>
      <div class="flex items-center space-x-4">
        <!-- 数据范围显示 -->
        <div class="text-sm text-gray-600">
          显示 {{ visibleData.length }} 个月数据
        </div>
        <!-- 重置按钮 -->
        <el-button size="small" @click="resetToDefault" :disabled="visibleData.length <= defaultMonths">
          重置
        </el-button>
      </div>
    </div>

    <!-- ECharts 折线图 -->
    <div ref="chartRef" :style="{ width: '100%', height: height + 'px' }"></div>

    <!-- 图例 -->
    <div class="mt-4 flex flex-wrap justify-center gap-4">
      <div v-for="subject in weaknessSubjects" :key="subject.name" class="flex items-center cursor-pointer"
        @click="toggleSubjectVisibility(subject.name)">
        <div class="w-3 h-3 rounded-full mr-2" :class="getSubjectColorClass(subject.name)"
          :style="{ opacity: isSubjectVisible(subject.name) ? 1 : 0.3 }"></div>
        <span class="text-sm" :class="isSubjectVisible(subject.name) ? 'text-gray-800' : 'text-gray-400'">
          {{ subject.name }}
        </span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, watch } from 'vue'

// 定义props
const props = defineProps({
  weaknessSubjects: {
    type: Array,
    required: true
  },
  height: {
    type: Number,
    default: 300
  }
})

// 默认显示月份数
const defaultMonths = 6

// 图表引用
const chartRef = ref(null)
let chart = null

// 可见数据范围
const visibleMonths = ref(defaultMonths)

// 生成模拟历史数据
const generateHistoryData = () => {
  const months = []
  const currentDate = new Date()

  // 生成24个月的数据（2年）
  for (let i = 23; i >= 0; i--) {
    const date = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1)
    months.push({
      month: date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'short' }),
      timestamp: date.getTime()
    })
  }

  return months
}

// 生成科目历史数据
const generateSubjectData = (subject) => {
  const baseScore = subject.score
  const volatility = 8 // 成绩波动范围
  const trend = Math.random() > 0.5 ? 1 : -1 // 随机趋势

  return generateHistoryData().map((month, index) => {
    // 模拟成绩变化：基础分数 + 随机波动 + 趋势变化
    const randomChange = (Math.random() - 0.5) * volatility
    const trendChange = (index / 24) * trend * 2 // 趋势变化
    const score = Math.max(0, Math.min(100, baseScore + randomChange + trendChange))

    return {
      month: month.month,
      score: Math.round(score),
      timestamp: month.timestamp
    }
  })
}

// 计算属性
const allHistoryData = computed(() => {
  return generateHistoryData()
})

const visibleData = computed(() => {
  return allHistoryData.value.slice(-visibleMonths.value)
})

const subjectHistoryData = computed(() => {
  const data = {}
  props.weaknessSubjects.forEach(subject => {
    data[subject.name] = generateSubjectData(subject)
  })
  return data
})

// 科目可见性状态
const visibleSubjects = ref(new Set(props.weaknessSubjects.map(s => s.name)))

// 科目颜色映射
const subjectColors = {
  '数学': '#ef4444',
  '语文': '#3b82f6',
  '英语': '#10b981',
  '物理': '#f59e0b',
  '化学': '#8b5cf6',
  '生物': '#ec4899'
}

// 方法
const getSubjectColor = (subjectName) => {
  return subjectColors[subjectName] || '#6b7280'
}

const getSubjectColorClass = (subjectName) => {
  const colorMap = {
    '数学': 'bg-red-500',
    '语文': 'bg-blue-500',
    '英语': 'bg-green-500',
    '物理': 'bg-yellow-500',
    '化学': 'bg-purple-500',
    '生物': 'bg-pink-500'
  }
  return colorMap[subjectName] || 'bg-gray-500'
}

const isSubjectVisible = (subjectName) => {
  return visibleSubjects.value.has(subjectName)
}

const toggleSubjectVisibility = (subjectName) => {
  if (visibleSubjects.value.has(subjectName)) {
    visibleSubjects.value.delete(subjectName)
  } else {
    visibleSubjects.value.add(subjectName)
  }
  updateChart()
}

const resetToDefault = () => {
  visibleMonths.value = defaultMonths
  visibleSubjects.value = new Set(props.weaknessSubjects.map(s => s.name))
  updateChart()
}

// 鼠标滚轮事件处理
const handleWheel = (event) => {
  event.preventDefault()

  if (event.deltaY < 0) {
    // 向上滚动，加载更多历史数据
    if (visibleMonths.value < allHistoryData.value.length) {
      visibleMonths.value = Math.min(visibleMonths.value + 3, allHistoryData.value.length)
      updateChart()
    }
  } else {
    // 向下滚动，减少显示数据
    if (visibleMonths.value > 3) {
      visibleMonths.value = Math.max(visibleMonths.value - 3, 3)
      updateChart()
    }
  }
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  // 动态导入 ECharts
  import('echarts').then((echarts) => {
    chart = echarts.init(chartRef.value)
    updateChart()

    // 添加鼠标滚轮事件监听
    chartRef.value.addEventListener('wheel', handleWheel, { passive: false })
  }).catch((error) => {
    console.error('Failed to load ECharts:', error)
    chartRef.value.innerHTML = `
      <div class="flex items-center justify-center h-full text-gray-500">
        <div class="text-center">
          <div class="i-mdi:chart-line w-16 h-16 mx-auto mb-2"></div>
          <p class="text-sm mb-2">历史趋势图</p>
          <p class="text-xs">请先安装: npm install echarts</p>
        </div>
      </div>
    `
  })
}

// 更新图表数据
const updateChart = () => {
  if (!chart) return

  const series = []
  const visibleSubjectsArray = Array.from(visibleSubjects.value)

  visibleSubjectsArray.forEach(subjectName => {
    const subjectData = subjectHistoryData.value[subjectName]
    if (subjectData) {
      const visibleSubjectData = subjectData.slice(-visibleMonths.value)
      series.push({
        name: subjectName,
        type: 'line',
        data: visibleSubjectData.map(item => item.score),
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          color: getSubjectColor(subjectName),
          width: 3
        },
        itemStyle: {
          color: getSubjectColor(subjectName)
        },
        areaStyle: {
          color: getSubjectColor(subjectName),
          opacity: 0.1
        }
      })
    }
  })

  const option = {
    title: {
      text: '短板科目历史成绩趋势',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#374151'
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'transparent',
      borderRadius: 8,
      textStyle: {
        color: '#fff'
      },
      formatter: function (params) {
        let result = `<div style="padding: 8px;"><div style="font-weight: bold; margin-bottom: 8px;">${params[0].axisValue}</div>`

        params.forEach(param => {
          const color = getSubjectColor(param.seriesName)
          result += `
            <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
              <span style="color: ${color}; font-weight: bold;">● ${param.seriesName}</span>
              <span style="color: #fff; margin-left: 20px;">${param.value}</span>
            </div>
          `
        })

        result += '</div>'
        return result
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: visibleData.value.map(item => item.month),
      axisLine: {
        lineStyle: {
          color: '#e5e7eb'
        }
      },
      axisLabel: {
        color: '#6b7280',
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      axisLine: {
        lineStyle: {
          color: '#e5e7eb'
        }
      },
      axisLabel: {
        color: '#6b7280',
        fontSize: 12
      },
      splitLine: {
        lineStyle: {
          color: '#f3f4f6',
          type: 'dashed'
        }
      }
    },
    series: series,
    backgroundColor: 'transparent'
  }

  chart.setOption(option)
}

// 监听数据变化
watch(() => props.weaknessSubjects, () => {
  if (chart) {
    visibleSubjects.value = new Set(props.weaknessSubjects.map(s => s.name))
    updateChart()
  }
}, { deep: true })

// 监听尺寸变化
watch(() => props.height, () => {
  if (chart) {
    setTimeout(() => {
      chart.resize()
    }, 100)
  }
})

// 组件挂载时初始化图表
onMounted(() => {
  initChart()
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  if (chartRef.value) {
    chartRef.value.removeEventListener('wheel', handleWheel)
  }
})
</script>

<style lang="scss" scoped>
.history-trend-chart {
  .chart-container {
    position: relative;
  }
}
</style> 